#!/usr/bin/env node
/*
  导入技能升级阈值：
  - 从数据库读取 skill_base 的技能名
  - 从 output/三种职业技能伤害以及耗蓝.csv 解析“升X级最少需要Y熟练度”
  - 插入 skill_upgrade_thresholds(skillName,nextGrade,requiredProficiency)
*/

const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');

// 加载 .env（优先根目录，其次 nestjs-app/.env）
try {
    const rootEnv = path.resolve(__dirname, '..', '.env');
    if (fs.existsSync(rootEnv)) {
        require('dotenv').config({ path: rootEnv });
    }
    const nestEnv = path.resolve(__dirname, '..', 'nestjs-app', '.env');
    if (fs.existsSync(nestEnv)) {
        require('dotenv').config({ path: nestEnv, override: false });
    }
} catch { }

async function main() {
    const csvPath = path.resolve(__dirname, '..', 'output/三种职业技能伤害以及耗蓝.csv');
    if (!fs.existsSync(csvPath)) {
        console.error(`未找到CSV: ${csvPath}`);
        process.exit(1);
    }

    // 读取数据库配置（沿用 nestjs 的 nextjs 数据库）
    const dbHost = process.env.DB_HOST || process.env.MYSQL_HOST || 'localhost';
    const dbPort = Number(process.env.DB_PORT || process.env.MYSQL_PORT || 3306);
    const dbUser = process.env.DB_USER || process.env.MYSQL_USER || 'root';
    const dbPass = process.env.DB_PASS || process.env.MYSQL_PASSWORD || '';
    const dbName = process.env.DB_NAME || process.env.MYSQL_DATABASE || 'nextjs';

    const conn = await mysql.createConnection({ host: dbHost, port: dbPort, user: dbUser, password: dbPass, database: dbName, charset: 'utf8mb4' });

    // 建表（若不存在）
    await conn.execute(`
    CREATE TABLE IF NOT EXISTS skill_upgrade_thresholds (
      id int(11) NOT NULL AUTO_INCREMENT,
      skillName varchar(100) NOT NULL,
      nextGrade int(11) NOT NULL,
      requiredProficiency int(11) NOT NULL,
      created_at datetime NOT NULL,
      updated_at datetime NULL,
      UNIQUE KEY uk_skill_grade (skillName, nextGrade),
      PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='技能升级阈值表';
  `);

    // 读取 skill_base
    const [skills] = await conn.execute("SELECT name FROM skill_base WHERE name IS NOT NULL AND name <> ''");
    const skillNames = new Set(skills.map(r => String(r.name).trim()).filter(Boolean));

    // 解析CSV
    const content = fs.readFileSync(csvPath, 'utf8');
    const lines = content.split(/\r?\n/);
    const cnToNum = { '二': 2, '三': 3, '四': 4, '五': 5 };
    const csvMap = new Map(); // name -> Map(nextGrade->need)
    for (const raw of lines) {
        if (!raw) continue;
        const cols = raw.split(',');
        if (cols.length < 9) continue;
        const name = (cols[0] || '').trim();
        const remark = (cols[8] || '').trim();
        if (!name || name === '技能名称') continue;
        const m = remark.match(/升([二三四五])级最少需要(\d+)熟练度/);
        if (!m) continue;
        const next = cnToNum[m[1]];
        const need = Number(m[2]);
        if (!next || Number.isNaN(need)) continue;
        if (!csvMap.has(name)) csvMap.set(name, new Map());
        csvMap.get(name).set(next, need);
    }

    const fallback = { 2: 200, 3: 500, 4: 2000, 5: 10000 };
    let inserted = 0;
    for (const name of skillNames) {
        for (const ng of [2, 3, 4, 5]) {
            const need = (csvMap.get(name)?.get(ng)) ?? fallback[ng];
            await conn.execute(
                `INSERT IGNORE INTO skill_upgrade_thresholds (skillName, nextGrade, requiredProficiency, created_at, updated_at) VALUES (?, ?, ?, NOW(), NULL)`,
                [name, ng, need]
            );
            inserted++;
        }
    }

    console.log(`✅ 导入完成：写入(或忽略重复) ${inserted} 条阈值。`);
    await conn.end();
}

main().catch(err => {
    console.error('❌ 导入失败:', err);
    process.exit(1);
});


